using System;
using NBusiness.Utilities;
using NBusiness.Data;
using System.Data.Common;

namespace Example.Business
{
    /// <summary>
    /// Summary description for Class1
    /// </summary>
    public partial class CompanyCollection
    {
        public override void Initialize()
        {
            this.Fetching += new EventHandler<FetchEventArgs>(FetchingByRegion);
        }

        #region Fetch By Region
        protected class FetchByRegionCriteria : CriteriaBase
        {
            private int _regionId;
            public int RegionId
            {
                get { return _regionId; }
            }
            public FetchByRegionCriteria(int regionId,int startIndex,int maxEntities, string sortField, SortOrder sortOrder)
                : base(startIndex,maxEntities,sortField,sortOrder)
            {
                _regionId = regionId;
            }
        }

        public static CompanyCollection FetchByRegion(int regionId)
        {
            int x;
            return FetchByRegion(regionId, -1, 0, null, SortOrder.None, out x);
        }
        public static CompanyCollection FetchByRegion(int regionId, int startIndex, int maxEntities, string sortField, SortOrder sortOrder, out int totalEntities)
        {
            FetchByRegionCriteria criteria = new FetchByRegionCriteria(
                regionId,
                startIndex,
                maxEntities,
                sortField,
                sortOrder);
            CompanyCollection list = new CompanyCollection(criteria);
            totalEntities = criteria.TotalEntities;
            return list;            
        }

        protected virtual void FetchingByRegion(object sender, FetchEventArgs e)
        {
            if(e.Criteria is FetchByRegionCriteria)
            {
                e.Criteria.TotalEntities = Settings.Instance.Database.FetchCollection(
                    e.Connection, 
                    "CompanyListFetchByRegion", 
                    e.Criteria,
                    Load, 
                    e.Criteria.StartIndex,
                    e.Criteria.MaxEntities,
                    e.Criteria.SortField,
                    e.Criteria.SortOrder,
                    new Parameter("@RegionId", ((FetchByRegionCriteria)e.Criteria).RegionId));
            }
        }
        #endregion
    }
}